<?php

namespace app\model;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;

class MessageSms
{
	public static function pickingupgoods($orderInfo)
	{

		$param['TemplateCode'] = 'storeOrderCode';
		$param['phone'] = $orderInfo['member']['telephone'];
		$param['param'] = json_encode([
			'name' => mb_substr(smsreplace($orderInfo['member']['nickname']), 0, 10),
			'store' => mb_substr(smsreplace($orderInfo['store']['title']), 0, 10)
		]);
		return self::send_sms($param);
	}

	/**
	 * 发送短信
	 * @param $AccessKeyId
	 * @param $Secret
	 * @param $params
	 * @return bool
	 * @throws ClientException
	 */
	static function send_sms($params)
	{
		if (empty($params['phone'])) {
			Test::create(['title' => '手机短信', 'info' => '手机号为空']);
			return false;
		}

		$smsConfig = Config::getconfig('sms');
		if (empty($smsConfig['status']) || empty($smsConfig['AccessKeyId'])) {
			Test::create(['title' => '手机短信', 'info' => '短信没配置']);
			return false;
		}

		if (empty($params['TemplateCode'])) {
			$TemplateCode = $smsConfig['TemplateCode'];
		} else {
			$TemplateCode = $smsConfig[$params['TemplateCode']];
		}

		if (empty($TemplateCode)) {
			Test::create(['title' => '手机短信', 'info' => '短信模板为空']);
			return false;
		}

		// 创建客户端
		AlibabaCloud::accessKeyClient(trim($smsConfig['AccessKeyId']), trim($smsConfig['Secret']))
			->regionId('cn-hangzhou')
			->asDefaultClient();
		try {
			$result = AlibabaCloud::rpc()
				->product('Dysmsapi')
				->version('2017-05-25')
				->action('SendSms')
				->host('dysmsapi.aliyuncs.com')
				->options([
					// 这里的参数可以在openAPI Explorer里面查看
					'query' => [
						'RigionId'     => 'cn_hangzhou',
						'PhoneNumbers' => $params['phone'],	// 输入的手机号
						'SignName'     => trim($smsConfig['SignName']),	// 签名信息
						'TemplateCode' => trim($TemplateCode),	// 短信模板id
						'TemplateParam' => $params['param']	// 可选，模板变量值，json格式
					]
				])->request();
			//print_r($result->toArray());
			Test::create(['title' => '手机短信', 'info' => serialize($params['param']) . $TemplateCode . serialize($result->toArray())]);
			return $result->toArray();
		} catch (ClientException $e) {
			return $e->getErrorMessage() . PHP_EOL;
		} catch (ServerException $e) {
			return $e->getErrorMessage() . PHP_EOL;
		}
	}
}
